package com.ytf.dogbox.util;

import android.util.Log;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;

/**
 * @author tiwolf_li
 * @Date on 2020/6/24
 * @Description Android 11使用"pm install -r "+path;好像升级会非常困难
 * 这个在Android11 也出现了问题，使用彭工编译的cmd接口就可以。但是使用在这里写的process = Runtime.getRuntime().exec("su");就会出现su: setgid failed: Operation not permitted异常
 */
public class InstallClient {


    private String path;
    private long length;
    public InstallClient(String str, long fileLength){
        this.path=str;
        this.length=fileLength;
    }

    public void installSlient() {
//        String cmd = "pm install -r "+path;
        String cmd="cat "+path+"| pm install -S "+length;
        Log.i("TAG", "installSlient: 升级的指令为="+cmd );
        Process process = null;
        DataOutputStream os = null;
        BufferedReader successResult = null;
        BufferedReader errorResult = null;
        StringBuilder successMsg = null;
        StringBuilder errorMsg = null;
        try {
            //静默安装需要root权限      目前需要手机再更新一次
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.write(cmd.getBytes());
            os.writeBytes("\n");
            os.writeBytes("exit\n");
            os.flush();
            //执行命令
            process.waitFor();
            //获取返回结果
            successMsg = new StringBuilder();
            errorMsg = new StringBuilder();
            successResult = new BufferedReader(new InputStreamReader(process.getInputStream()));
            errorResult = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            String s;
            while ((s =successResult.readLine()) != null) {
                successMsg.append(s);
            }
            while ((s = errorResult.readLine())!= null) {
                errorMsg.append(s);
            }
        } catch (Exception e) {
            //Error running exec(). Command: [su] Working Directory: null Environment: null   可能是这个手机没有root的权限
            e.printStackTrace();
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (process != null) {
                    process.destroy();
                }
                if (successResult != null) {
                    successResult.close();
                }
                if (errorResult != null) {
                    errorResult.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        //显示结果
//        tvTest.setText("成功消息：" + successMsg.toString() +"\n" + "错误消息: " + errorMsg.toString());
        Log.e("tag", "成功消息：" + successMsg.toString() +"\n" + "错误消息: " + errorMsg.toString());
    }

}
